#!/usr/bin/python
#coding=utf8

# 设置系统运行的默认编码类型
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# 导入系统模块
import os
import logging
import traceback
import tornado.web
import tornado.gen
import tornado.ioloop
import tornado.options as tdoptions
import concurrent.futures as futures

#导入自定义的模块
import commlib.Constant as COMMC
from tornado.log import LogFormatter

from commlib.Logger import Logger
from controller.error.NotFound import Handler as NotFoundHandler


# 定义命令行参数选项
tdoptions.define("url",  default='http://www.example.com', help="Url to show in HTML")
tdoptions.define("host", default='www.example.com', help="Run server on a specific host")
tdoptions.define("port", default=80, help="Run server on a specific port", type=int)

class Application(tornado.web.Application):

    def __init__(self):
        self.settings = None
        self.handlers = None

        # 初始化基础配置信息
        self._init_settings()

        # 初始化日志等输出器
        self._init_outputer()

        # 初始化路由映射表
        self._init_handlers()

    @tornado.gen.coroutine
    def init_application_start(self):
        """
        异步初始化基础应用
        """
        # 初始化数据库连接信息
        yield self._init_database()

        # 调用父类初始化函数
        tornado.web.Application.__init__(self, self.handlers, **self.settings)

    def _init_settings(self):
        # 判断是否配置了基地址
        if not tdoptions.options.url:
            if tdoptions.options.port == 80:
                tdoptions.options.url = "http://%s/" % tdoptions.options.host
            elif tdoptions.options.port == 443:
                tdoptions.options.url = "https://%s/" % tdoptions.options.host
            else:
                tdoptions.options.url = "http://%s:%d/" % (tdoptions.options.host, tdoptions.options.port)


        self.settings = {
            "debug" : COMMC.SYS_RTIME_DEBUG,
            "caches": {},
            "application": self,
            "xsrf_cookies": True,
            "compress_response": True,
            "cookie_secret": COMMC.SYS_RTIME_COOKIE_SECRET,
            "session": {
                "driver": "file",
                "driver_settings": { "host": COMMC.LOG_SESSION_PATH },
                "cache_driver": True,
                "force_persistence": True,
                "cookie_config": { "httponly": True, "expires_days": 1, "expires": False}
            },
            "base_url": tdoptions.options.url,
            "default_handler_class": NotFoundHandler,
            "thread_pool": futures.ThreadPoolExecutor(8),
            "static_path": os.path.join(os.getcwd(), "view", "static"),
            "template_path": os.path.join(os.getcwd(), "view", "template"),
        }


    def _init_outputer(self):
        # 初始化默认日志系统
        # 透传给处理器
        self.settings["logger"] = self._init_tornado_logger()


    def _init_tornado_logger(self):
        """
        初始化 tornado 系统默认日志系统
        """
        datefmt = '%Y-%m-%d %H:%M:%S'
        contentfmt = '%(color)s[%(asctime)s][%(levelname)s]%(end_color)s: %(message)s'
        formatter = LogFormatter(color=True, datefmt=datefmt, fmt=contentfmt)
        # 修改日志内容格式
        logger = logging.getLogger()
        # 设置日志级别
        logger.setLevel(logging.DEBUG)
        # 修改格式
        for logHandler in logger.handlers:
            logHandler.setFormatter(formatter)
        # 返回
        return logging


    def _init_handlers(self):
        # 校验一次即可
        self.handlers = [
            # 默认首页
            (r"^/18A6C6791B97447C8D0A578C129DD270"               , "controller.ezca.Menu.Handler"),
            (r"^/18A6C6791B97447C8D0A578C129DD270/caget/tps"          , "controller.ezca.Tps.Handler"),
            (r"^/18A6C6791B97447C8D0A578C129DD270/caget/water"    , "controller.ezca.Water.Handler"),
            (r"^/18A6C6791B97447C8D0A578C129DD270/caget/target"   , "controller.ezca.Target.Handler"),
            (r"^/18A6C6791B97447C8D0A578C129DD270/caget/container", "controller.ezca.Container.Handler"),
            (r"^/18A6C6791B97447C8D0A578C129DD270/caget/shield"   , "controller.ezca.Shield.Handler"),
            (r"^/18A6C6791B97447C8D0A578C129DD270/caget/reflect"  , "controller.ezca.Reflect.Handler"),
            (r"^/18A6C6791B97447C8D0A578C129DD270/caget/temper"   , "controller.ezca.Temper.Handler"),
            (r"^/18A6C6791B97447C8D0A578C129DD270/caget/comeon"   , "controller.ezca.Comeon.Handler"),
        ]

    @tornado.gen.coroutine
    def _init_database(self):
        pass


if __name__ == "__main__":
    try:
        # 解析命令行参数
        tdoptions.parse_command_line()
        # 实例化应用
        webSvrApp = Application()
        # 初始化基础值
        webSvrApp.init_application_start()
        # 启动端口监听
        webSvrApp.listen(tdoptions.options.port, xheaders=True)
        # 启动事件监听
        tornado.ioloop.IOLoop.instance().start()
    except:
        print(traceback.print_exc())
    finally:
        sys.exit(0)

